//
//  HomeViewController.m
//  Final
//
//  Created by Lenrony on 2021/12/2.
//  Copyright © 2021 Lenrony. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "../ModelController.h"
#import "HomeViewController.h"
#import "DetailViewController.h"
#import "PostViewController.h"
#import "FieldViewController.h"
#import "./Views/ArticleView.h"

@interface HomeViewController()

@property (nonatomic) BOOL Chronological;    // 是否按时间顺序排序
@property (strong, nonatomic) UIButton *popularButton;   // 按热度排序按钮
@property (strong, nonatomic) UIButton *chronologicalButton; // 按发布时间排序按钮
@property (strong, nonatomic) UIButton *lastButton;  // 作为热度排序按钮和时间排序按钮的互斥选中按钮
@property (strong, nonatomic) UIButton *addButton;   // 发布新帖子的按钮
@property (strong, nonatomic) UIAlertController* alert;
@property (strong, nonatomic) NSMutableArray *rawUsers;
@property (strong ,nonatomic) NSMutableArray *articles;
@property (strong, nonatomic) ArticleView *artv;

@property(strong, nonatomic) ModelController *mc;

@end

@implementation HomeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    _mc = [ModelController getInstance];
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"gray.png"]];
    [self setupToolBar];
    [self setupButtons];
    [self setupLabel];
    [self setupCollectionView];
    [self.view insertSubview:_addButton aboveSubview:_artv];
}

- (void)setupToolBar {
    UIToolbar *tools = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 140)];
    tools.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:tools];
    
    UIImage *icon1 = [UIImage imageNamed:@"gift.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    icon1 = [icon1 imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIButton *item1btr = [[UIButton alloc] init];
    [item1btr setBackgroundImage:icon1 forState:UIControlStateNormal];
    item1btr.tintColor = [UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0];
    [item1btr setTitle:@"二手闲置" forState:UIControlStateNormal];
    item1btr.titleLabel.font = [UIFont systemFontOfSize:11];
    [item1btr setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [item1btr setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -80, 0)];
    [item1btr.widthAnchor constraintEqualToConstant:45].active = YES;
    [item1btr.heightAnchor constraintEqualToConstant:45].active = YES;
    [item1btr addTarget:self action:@selector(firstClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item1 = [[UIBarButtonItem alloc] initWithCustomView:item1btr];
    
    UIImage *icon2 = [UIImage imageNamed:@"ic_light_on.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    icon2 = [icon2 imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIButton *item2btr = [[UIButton alloc] init];
    [item2btr setBackgroundImage:icon2 forState:UIControlStateNormal];
    item2btr.tintColor = [UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0];
    [item2btr setTitle:@"打听求助" forState:UIControlStateNormal];
    item2btr.titleLabel.font = [UIFont systemFontOfSize:11];
    [item2btr setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [item2btr setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -80, 0)];
    [item2btr.widthAnchor constraintEqualToConstant:45].active = YES;
    [item2btr.heightAnchor constraintEqualToConstant:45].active = YES;
    [item2btr addTarget:self action:@selector(secondClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item2 = [[UIBarButtonItem alloc] initWithCustomView:item2btr];
    
    UIImage *icon3 = [UIImage imageNamed:@"ic_heart.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    icon3 = [icon3 imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIButton *item3btr = [[UIButton alloc] init];
    [item3btr setBackgroundImage:icon3 forState:UIControlStateNormal];
    item3btr.tintColor = [UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0];
    [item3btr setTitle:@"青青子衿" forState:UIControlStateNormal];
    item3btr.titleLabel.font = [UIFont systemFontOfSize:11];
    [item3btr setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [item3btr setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -80, 0)];
    [item3btr.widthAnchor constraintEqualToConstant:45].active = YES;
    [item3btr.heightAnchor constraintEqualToConstant:45].active = YES;
    [item3btr addTarget:self action:@selector(thirdClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item3 = [[UIBarButtonItem alloc] initWithCustomView:item3btr];
    
    UIImage *icon4 = [UIImage imageNamed:@"ic_umbrella.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    icon4 = [icon4 imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIButton *item4btr = [[UIButton alloc] init];
    [item4btr setBackgroundImage:icon4 forState:UIControlStateNormal];
    item4btr.tintColor = [UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0];
    [item4btr setTitle:@"瓜田趣事" forState:UIControlStateNormal];
    item4btr.titleLabel.font = [UIFont systemFontOfSize:11];
    [item4btr setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [item4btr setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -80, 0)];
    [item4btr.widthAnchor constraintEqualToConstant:45].active = YES;
    [item4btr.heightAnchor constraintEqualToConstant:45].active = YES;
    [item4btr addTarget:self action:@selector(forthClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item4 = [[UIBarButtonItem alloc] initWithCustomView:item4btr];
    
    UIImage *icon5 = [UIImage imageNamed:@"ic_meeting.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil];
    icon5 = [icon5 imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    UIButton *item5btr = [[UIButton alloc] init];
    [item5btr setBackgroundImage:icon5 forState:UIControlStateNormal];
    item5btr.tintColor = [UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0];
    [item5btr setTitle:@"校园招聘" forState:UIControlStateNormal];
    item5btr.titleLabel.font = [UIFont systemFontOfSize:11];
    [item5btr setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [item5btr setTitleEdgeInsets:UIEdgeInsetsMake(0, 0, -80, 0)];
    [item5btr.widthAnchor constraintEqualToConstant:45].active = YES;
    [item5btr.heightAnchor constraintEqualToConstant:45].active = YES;
    [item5btr addTarget:self action:@selector(fifthClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *item5 = [[UIBarButtonItem alloc] initWithCustomView:item5btr];
    
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    
    tools.items = @[item1,flexibleSpace,item2,flexibleSpace,item3,flexibleSpace,item4,flexibleSpace,item5];
}

- (void) setupCollectionView {
    self.articles = [[ModelController getInstance] getArticleWithType:0 andMode:@"hot"];
    
    if (self.articles == nil) {
        [self showAlertWithTitle:@"联网失败" andText:@"请确认网络连接正常并刷新！"];
        self.articles = [[NSMutableArray alloc] init];
    }
    if (self.articles.count == 0) {
        [self showAlertWithTitle:@"当前没有帖子" andText:@"未找到相关帖子..."];
        self.articles = [[NSMutableArray alloc] init];
    }
    
    self.rawUsers = [[NSMutableArray alloc] init];
    for (Article *art in self.articles) {
        [self.rawUsers addObject:[[ModelController getInstance] getRawUser:art.u_id]];
    }
    
    self.artv = [[ArticleView alloc] initWithViewController:self andRawUsers:self.rawUsers andArticles:self.articles];
    [self.artv setFrame:CGRectMake(0, 200, [UIScreen mainScreen].bounds.size.width, self.view.frame.size.height-200-[[UIApplication sharedApplication] statusBarFrame].size.height)];
    [self.artv.articlesView setFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.view.frame.size.height-200-[[UIApplication sharedApplication] statusBarFrame].size.height)];
    [self.view addSubview:self.artv];
}

- (void)updateCollectionView {
    if (self.Chronological) {
        self.articles = [[ModelController getInstance] getArticleWithType:0 andMode:@"time"];
    }
    else {
        self.articles = [[ModelController getInstance] getArticleWithType:0 andMode:@"hot"];
    }
    if (self.articles == nil) {
        [self showAlertWithTitle:@"联网失败" andText:@"请确认网络连接正常并刷新！"];
        self.articles = [[NSMutableArray alloc] init];
    }
    if (self.articles.count == 0) {
        [self showAlertWithTitle:@"当前没有帖子" andText:@"未找到相关帖子..."];
        self.articles = [[NSMutableArray alloc] init];
    }
    
    self.rawUsers = [[NSMutableArray alloc] init];
    for (Article *art in self.articles) {
        [self.rawUsers addObject:[[ModelController getInstance] getRawUser:art.u_id]];
    }
    
    [self.artv updateCollectionViewWithArticles:self.articles andRawUsers:self.rawUsers];
}

- (void) setupButtons {
    self.popularButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-160, 155, 70, 30)];
    [self.popularButton setTitle:@"按热度" forState:UIControlStateNormal];
    [self.popularButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.popularButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
    self.popularButton.layer.cornerRadius = 5;
    self.popularButton.layer.masksToBounds = YES;
    [self.popularButton addTarget:self action:@selector(sortClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.popularButton];
    
    self.chronologicalButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-80, 155, 70, 30)];
    [self.chronologicalButton setTitle:@"按时间" forState:UIControlStateNormal];
    [self.chronologicalButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [self.chronologicalButton.titleLabel setFont:[UIFont systemFontOfSize:15]];
    self.chronologicalButton.layer.cornerRadius = 5;
    self.chronologicalButton.layer.masksToBounds = YES;
    [self.chronologicalButton addTarget:self action:@selector(sortClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.chronologicalButton];
    
    // 默认按热度排序
    self.Chronological = NO; // 按话题热度的顺序排列
    [self.popularButton setBackgroundColor:[UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0]];
    [self.popularButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.lastButton = self.popularButton;
    
    [self setupAddButton];
}

- (void) setupAddButton {
    self.addButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width-80, self.view.frame.size.height-160, 60, 60)];
    [self.addButton setImage:[UIImage imageNamed:@"jiahao.png" inBundle:[NSBundle mainBundle] compatibleWithTraitCollection:nil] forState:UIControlStateNormal];
    [self.addButton setBackgroundColor:[UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0]];
    [self.addButton setTintColor:[UIColor whiteColor]];
    self.addButton.layer.cornerRadius = 30;
    self.addButton.layer.masksToBounds = YES;
    [self.addButton addTarget:self action:@selector(addNewPostClick:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.addButton];
}

- (void) setupLabel {
    UILabel *sortLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 160, 80, 20)];
    sortLabel.text = @"排序方式";
    sortLabel.font = [UIFont systemFontOfSize:17];
    sortLabel.textColor = [UIColor blackColor];
    [self.view addSubview:sortLabel];
}

- (void) firstClick:(id)sender {
    NSLog(@"二手闲置");
    FieldViewController *fvc = [[FieldViewController alloc] initWithField:1];
    [self.navigationController pushViewController:fvc animated:YES];
}

- (void) secondClick:(id)sender {
    NSLog(@"打听求助");
    FieldViewController *fvc = [[FieldViewController alloc] initWithField:2];
    [self.navigationController pushViewController:fvc animated:YES];
}

- (void) thirdClick:(id)sender {
    NSLog(@"青青子衿");
    FieldViewController *fvc = [[FieldViewController alloc] initWithField:3];
    [self.navigationController pushViewController:fvc animated:YES];
}

- (void) forthClick:(id)sender {
    NSLog(@"瓜田趣事");
    FieldViewController *fvc = [[FieldViewController alloc] initWithField:4];
    [self.navigationController pushViewController:fvc animated:YES];
}

- (void) fifthClick:(id)sender {
    NSLog(@"校园招聘");
    FieldViewController *fvc = [[FieldViewController alloc] initWithField:5];
    [self.navigationController pushViewController:fvc animated:YES];
}

- (void) sortClick:(id)sender {
    UIButton *btn = (UIButton *)sender;
    if (self.lastButton != btn) {
        [btn setBackgroundColor:[UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0]];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self.lastButton setBackgroundColor:[UIColor clearColor]];
        [self.lastButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        // 更改collection view的排列方式
        if (btn == self.chronologicalButton) {
            self.Chronological = YES;
            NSLog(@"按时间排序");
            [self updateCollectionView];
        }
        else {
            self.Chronological = NO;
            NSLog(@"按热度排序");
            [self updateCollectionView];
        }
        self.lastButton = btn;
    }
}

- (void) addNewPostClick:(id)sender {
    if (_mc.cur_user == nil) {
        [self showAlertWithTitle:@"创建帖子失败" andText:@"请先登录！"];
    }
    else {
        PostViewController *pvc = [[PostViewController alloc] init];
        [self.navigationController pushViewController:pvc animated:YES];
    }
}

- (void)showAlertWithTitle: (NSString*)title
                   andText: (NSString*)text
{
    self.alert = [UIAlertController alertControllerWithTitle:title message:text preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:self.alert animated:YES completion:nil];
    [self performSelector:@selector(hideAlert) withObject:self.alert afterDelay:1.5];
}

- (void)hideAlert
{
    [self.alert dismissViewControllerAnimated:YES completion:^{
        if(self.mc.cur_user != nil){
            [self viewWillAppear:YES];
        }
    }];
}

@end
